<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      .list {
        width: 200px;
        height: 100px;
        background: skyblue;
        overflow: auto;
      }
      .news {
        height: 30px;
      }
      .list::-webkit-scrollbar {
        /*滚动条整体样式*/
        width: 10px; /*高宽分别对应横竖滚动条的尺寸*/
        height: 1px;
      }
      .list::-webkit-scrollbar-thumb {
        /*滚动条里面小方块*/
        border-radius: 10px;
        box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
        background: #535353;
      }
      .list::-webkit-scrollbar-track {
        /*滚动条里面轨道*/
        box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
        border-radius: 10px;
        background: #ededed;
      }
    </style>
  </head>
  <body>
    <div id="root"></div>
    <script src="https://cdn.bootcdn.net/ajax/libs/react/17.0.1/umd/react.development.min.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/react-dom/17.0.1/umd/react-dom.development.min.js"></script>
    <script src="https://cdn.staticfile.org/babel-standalone/6.26.0/babel.min.js"></script>
    <script type="text/babel">
      const { Component, useState, useEffect, useMemo } = React;
      function NewList() {
        const [newsArr, setNewsArr] = useState([]);
        const [list, setList] = useState({});

        function snapshotListHeight() {
          return list.scrollHeight;
        }
        const height = useMemo(() => snapshotListHeight());
        useEffect(() => {
          const timer = setInterval(() => {
            setNewsArr((newsArr) => {
              const news = `新闻${newsArr.length + 1}`;
              return [news, ...newsArr];
            });
          }, 1000);
          console.log("snapshotListHeight", snapshotListHeight());
          console.log("height", height);
          console.log("list.scrollTop", list.scrollTop);
          list.scrollTop += list.scrollHeight - height;
          return () => {
            clearInterval(timer);
          };
        });
        return (
          <ul className="list" ref={(s) => setList(s)}>
            {newsArr.map((item, index) => {
              return (
                <li key={index + "_" + Math.random()} className="news">
                  {item}
                </li>
              );
            })}
          </ul>
        );
      }
      const App = (
        <div>
          <NewList></NewList>
        </div>
      );
      ReactDOM.render(App, document.getElementById("root"));
    </script>
  </body>
</html>
